package com.example.gokuplayalong.service.home;


import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.widget.ViewPager2;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.gokuplayalong.MainActivity;
import com.example.gokuplayalong.R;
import com.example.gokuplayalong.bases.beans.AppParams;
import com.example.gokuplayalong.bases.beans.Beans;
import com.example.gokuplayalong.bases.exception.ExceptionUtils;
import com.example.gokuplayalong.bases.network.NetWorkInterface;
import com.example.gokuplayalong.bases.network.updown.DownLoad;
import com.example.gokuplayalong.bases.network.updown.UploadDownInterface;
import com.example.gokuplayalong.bases.tools.Logger;
import com.example.gokuplayalong.bases.tools.Tools;
import com.example.gokuplayalong.service.fragments.main.UserMainMessage;
import com.example.gokuplayalong.service.fragments.main.UserMainProfile;
import com.example.gokuplayalong.service.fragments.main.UserMainPublish;
import com.example.gokuplayalong.service.fragments.main.UserMainReceive;
import com.example.gokuplayalong.service.fragments.main.UserMainViewPagerAdapter;
import com.example.gokuplayalong.service.fragmentsmanage.BaseFragment;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.dialogs.MessageDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener;
import com.mob.pushsdk.MobPush;
import com.mob.pushsdk.MobPushCallback;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class HomeMain extends BaseFragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    View rootView;
    List<Fragment> fragments = new ArrayList<>();
    private ViewPager2 mHomeMainViewpager2;
    private LinearLayout mHomeMainBottom1;
    private LinearLayout mHomeMainBottom2;
    private LinearLayout mHomeMainBottom3;
    private LinearLayout mHomeMainBottom4;
    private ImageView mHomeMainBottom1Imageview;
    private ImageView mHomeMainBottom2Imageview;
    private ImageView mHomeMainBottom3Imageview;
    private ImageView mHomeMainBottom4Imageview;
    public UserMainViewPagerAdapter userMainViewPagerAdapter;
    MessageDialog messageDialog;
    CustomDialog customDialogForNewUserTask;
    public Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 0: {

                    try {

                        if (mHomeMainViewpager2.getCurrentItem() == 0) {
                            userMainViewPagerAdapter.setMaxLifeCycle(0, Lifecycle.State.STARTED);
                            userMainViewPagerAdapter.setMaxLifeCycle(0, Lifecycle.State.RESUMED);
                        }
                        else if (mHomeMainViewpager2.getCurrentItem() == 1) {
                            userMainViewPagerAdapter.setMaxLifeCycle(1, Lifecycle.State.STARTED);
                            userMainViewPagerAdapter.setMaxLifeCycle(1, Lifecycle.State.RESUMED);
                        }
                        else if (mHomeMainViewpager2.getCurrentItem() == 2) {
                            userMainViewPagerAdapter.setMaxLifeCycle(2, Lifecycle.State.STARTED);
                            userMainViewPagerAdapter.setMaxLifeCycle(2, Lifecycle.State.RESUMED);
                        }
                        else if (mHomeMainViewpager2.getCurrentItem() == 3) {
                            userMainViewPagerAdapter.setMaxLifeCycle(3, Lifecycle.State.STARTED);
                            userMainViewPagerAdapter.setMaxLifeCycle(3, Lifecycle.State.RESUMED);
                        }
                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }
                }
                break;
                case 1:

                    requireActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                mHomeMainViewpager2.setCurrentItem(0);
                            } catch (Throwable e) {
                                ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                            }
                        }
                    });
                    break;
                case 2:
                    break;
                case 3: {


                }
                break;
                case 6: {

                }
                break;
            }
        }
    };


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null)
            rootView = inflater.inflate(R.layout.fragment_home_main, container, false);
        initView();
        return rootView;
    }

    private void initView() {


        mHomeMainViewpager2 = (ViewPager2) rootView.findViewById(R.id.home_main_viewpager2);

        mHomeMainBottom1 = rootView.findViewById(R.id.home_main_bottom_1);
        mHomeMainBottom2 = rootView.findViewById(R.id.home_main_bottom_2);
        mHomeMainBottom3 = rootView.findViewById(R.id.home_main_bottom_3);
        mHomeMainBottom4 = rootView.findViewById(R.id.home_main_bottom_4);

        mHomeMainBottom1Imageview = rootView.findViewById(R.id.home_main_bottom_1_imageview);
        mHomeMainBottom2Imageview = rootView.findViewById(R.id.home_main_bottom_2_imageview);
        mHomeMainBottom3Imageview = rootView.findViewById(R.id.home_main_bottom_3_imageview);
        mHomeMainBottom4Imageview = rootView.findViewById(R.id.home_main_bottom_4_imageview);

        if (!fragments.isEmpty()) fragments.clear();
        fragments.add(new UserMainReceive());
        fragments.add(new UserMainPublish());
        fragments.add(new UserMainMessage());
        fragments.add(new UserMainProfile());


        mHomeMainViewpager2.setUserInputEnabled(false);
        mHomeMainViewpager2.setOffscreenPageLimit(fragments.size());
        userMainViewPagerAdapter = new UserMainViewPagerAdapter(getChildFragmentManager(), getLifecycle(), fragments);
        mHomeMainViewpager2.setAdapter(userMainViewPagerAdapter);

        mHomeMainViewpager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                mHomeMainBottom1Imageview.setSelected(false);
                mHomeMainBottom2Imageview.setSelected(false);
                mHomeMainBottom3Imageview.setSelected(false);
                mHomeMainBottom4Imageview.setSelected(false);

                switch (position) {
                    case 0: {
                        userMainViewPagerAdapter.setMaxLifeCycle(0, Lifecycle.State.RESUMED);
                        userMainViewPagerAdapter.setMaxLifeCycle(1, Lifecycle.State.STARTED);
                        userMainViewPagerAdapter.setMaxLifeCycle(2, Lifecycle.State.STARTED);
                        userMainViewPagerAdapter.setMaxLifeCycle(3, Lifecycle.State.STARTED);
                        mHomeMainBottom1Imageview.setSelected(true);

                    }
                    break;
                    case 1: {
                        userMainViewPagerAdapter.setMaxLifeCycle(0, Lifecycle.State.STARTED);
                        userMainViewPagerAdapter.setMaxLifeCycle(1, Lifecycle.State.RESUMED);
                        userMainViewPagerAdapter.setMaxLifeCycle(2, Lifecycle.State.STARTED);
                        userMainViewPagerAdapter.setMaxLifeCycle(3, Lifecycle.State.STARTED);
                        mHomeMainBottom2Imageview.setSelected(true);

                    }
                    break;
                    case 2: {
                        userMainViewPagerAdapter.setMaxLifeCycle(0, Lifecycle.State.STARTED);
                        userMainViewPagerAdapter.setMaxLifeCycle(1, Lifecycle.State.STARTED);
                        userMainViewPagerAdapter.setMaxLifeCycle(2, Lifecycle.State.RESUMED);
                        userMainViewPagerAdapter.setMaxLifeCycle(3, Lifecycle.State.STARTED);
                        mHomeMainBottom3Imageview.setSelected(true);
                    }
                    break;
                    case 3: {
                        userMainViewPagerAdapter.setMaxLifeCycle(0, Lifecycle.State.STARTED);
                        userMainViewPagerAdapter.setMaxLifeCycle(1, Lifecycle.State.STARTED);
                        userMainViewPagerAdapter.setMaxLifeCycle(2, Lifecycle.State.STARTED);
                        userMainViewPagerAdapter.setMaxLifeCycle(3, Lifecycle.State.RESUMED);
                        mHomeMainBottom4Imageview.setSelected(true);
                    }
                    break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }
        });
        mHomeMainBottom1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHomeMainViewpager2.setCurrentItem(0, false);
            }
        });
        mHomeMainBottom2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHomeMainViewpager2.setCurrentItem(1, false);
            }
        });
        mHomeMainBottom3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHomeMainViewpager2.setCurrentItem(2, false);
            }
        });
        mHomeMainBottom4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHomeMainViewpager2.setCurrentItem(3, false);
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initChanged();
            Message message = new Message();
            message.what = 0;
            handler.sendMessage(message);
        }
        else {

            if (messageDialog != null) messageDialog.dismiss();
            if (customDialogForNewUserTask != null) customDialogForNewUserTask.dismiss();
        }
    }

    private void initChanged() {
        try {

            File file = new File(AppParams.getInstance().mediaDir, "keyParams.txt");

            if (file.exists()) {
                BufferedReader reader = new BufferedReader(new FileReader(file.getAbsoluteFile()));
                String line;
                while ((line = reader.readLine()) != null) {
                    AppParams.getInstance().appCurrentUser.setJsonObject(JSON.parseObject(line));
                }
                reader.close();
            }
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
        try {
            getKeyParams();
            upgradeProcess();
            pushRid();
            checkInstallState();


        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

    private void pushRid() {
        if (AppParams.getInstance().appRunParams.getJsonObject().getIntValue("ridFlag") == 0) {

            MobPush.getRegistrationId(new MobPushCallback<String>() {
                @Override
                public void onCallback(String s) {
                    try {
                        AppParams.getInstance().mobRid = s;
                        Beans beansIn = new Beans();
                        beansIn.getJsonObject()
                                .put("phone", AppParams.getInstance().appCurrentUser.getJsonObject()
                                        .getString("phone"));
                        beansIn.getJsonObject().put("mobRid", AppParams.getInstance().mobRid);

                        AppParams.getNewNetWork()
                                .setInterface(new NetWorkInterface() {

                                    @Override
                                    public int success(String msg) {
                                        requireActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                try {
                                                    JSONObject msgFromServer = JSON.parseObject(msg);
                                                    if (Objects.equals(msgFromServer.getString("result"), "成功")) {
                                                        AppParams.getInstance().appRunParams.getJsonObject()
                                                                .put("ridFlag", 1);
                                                    }
                                                } catch (Throwable e) {
                                                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                                }
                                            }
                                        });
                                        return 0;
                                    }

                                    @Override
                                    public int failed(String msg) {
                                        return 0;
                                    }
                                })
                                .execute(AppParams.getInstance().baseUrl + "/pushRid", beansIn.getJsonObject()
                                        .toJSONString());

                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }
                }
            });
        }
    }

    private void upgradeProcess() {
        try {
            if (AppParams.getInstance().appRunParams.getJsonObject()
                    .getIntValue("upgradeFlag") == 0) {
                try {
                    AppParams.getNewNetWork().setInterface(new NetWorkInterface() {
                        @Override
                        public int success(String msg) {
                            try {
                                JSONObject msgFromServer = JSON.parseObject(msg);
                                if (Objects.equals(msgFromServer.getString("result"), "成功")) {
                                    try {

                                        AppParams.getInstance().appRunParams.getJsonObject()
                                                .put("upgradeFlag", 1);

                                        JSONObject versionInfo = JSON.parseObject(msgFromServer.getString("versionInfo"));
                                        if (versionInfo.getString("newVersion")
                                                .compareTo(DownLoad.getVersionName()) > 0 && versionInfo.getIntValue("testFinish") == 1) {
                                            messageDialog = MessageDialog.build();
                                            messageDialog.setTitle("有新版本");
                                            messageDialog.setCancelable(false);
                                            messageDialog.setMessage("发现新版本\n" + versionInfo.getString("newVersion") + "\n" + versionInfo.getString("versionDesc"));
                                            messageDialog.setOkButtonClickListener(new OnDialogButtonClickListener<MessageDialog>() {
                                                @Override
                                                public boolean onClick(MessageDialog dialog, View v) {

                                                    try {
                                                        File file = new File(AppParams.getInstance().mediaDir, AppParams.getInstance().apkName);
                                                        DownLoad.getInstance()
                                                                .downloadFile(AppParams.getInstance().uploadMediaLocationServer + "/" + AppParams.getInstance().apkName, file.getAbsolutePath(), new UploadDownInterface() {
                                                                    @Override
                                                                    public void uploadSuccess(String msg) {

                                                                    }

                                                                    @Override
                                                                    public void uploadFailed(IOException e) {

                                                                    }

                                                                    @Override
                                                                    public void downSuccess() {
                                                                        requireActivity().runOnUiThread(new Runnable() {
                                                                            @Override
                                                                            public void run() {
                                                                                try {
                                                                                    File apkFile = new File(AppParams.getInstance().mediaDir, AppParams.getInstance().apkName);
                                                                                    if (apkFile.exists()) {
                                                                                        DownLoad.installApk(MainActivity.getInstance(), apkFile.getAbsolutePath());
                                                                                    }
                                                                                } catch (
                                                                                        Throwable e) {
                                                                                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                                                                }
                                                                            }
                                                                        });
                                                                    }

                                                                    @Override
                                                                    public void downFailed() {

                                                                    }
                                                                });

                                                        if (versionInfo.getIntValue("isForce") == 1) {
                                                            MessageDialog.show("提示", "下载中,请稍等...")
                                                                    .setCancelable(false);
                                                        }
                                                    } catch (Throwable e) {
                                                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                                    }
                                                    return false;
                                                }
                                            });

                                            if (versionInfo.getIntValue("isForce") == 1) {
                                                messageDialog.setOkButton("立即更新");
                                            }
                                            else {
                                                messageDialog.setOkButton("后台更新");
                                                messageDialog.setCancelButton("稍后更新");
                                            }
                                            messageDialog.show();
                                        }
                                    } catch (Throwable e) {
                                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                    }
                                }

                            } catch (Throwable e) {
                                ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                            }
                            return 0;
                        }

                        @Override
                        public int failed(String msg) {
                            return 0;
                        }
                    }).execute(AppParams.getInstance().baseUrl + "/checkUpgrade", "{}");

                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

    private void getKeyParams() {
        try {
            Beans beansIn = new Beans();
            beansIn.getJsonObject()
                    .put("phone", AppParams.getInstance().appCurrentUser.getJsonObject()
                            .getString("phone"));
            AppParams.getNewNetWork()
                    .setInterface(new NetWorkInterface() {
                        @Override
                        public int success(String msg) {
                            requireActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        JSONObject msgFromServer = JSON.parseObject(msg);
                                        if (Objects.equals(msgFromServer.getString("result"), "成功")) {


                                            AppParams.getInstance().appRunParams.getJsonObject()
                                                    .put("keyParamFlag", 1);
                                            JSONObject param = JSON.parseObject(msgFromServer.getString("params"));
                                            AppParams.getInstance().appCurrentUser.getJsonObject()
                                                    .putAll(param);
                                            AppParams.getInstance().appCurrentUser.getJsonObject()
                                                    .put("merchantInfo", msgFromServer.getString("merchantInfo"));
                                            try {
                                                File file = new File(AppParams.getInstance().mediaDir, "keyParams.txt");
                                                if (!file.exists()) {
                                                    file.createNewFile();
                                                }
                                                FileWriter fileWriter = new FileWriter(file.getAbsoluteFile(), false);
                                                fileWriter.write(AppParams.getInstance().appCurrentUser.getJsonObject()
                                                        .toJSONString());
                                                fileWriter.close();


                                            } catch (Throwable e) {
                                                ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                            }
                                        }
                                        WaitDialog.dismiss();
                                    } catch (Throwable e) {
                                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                    }
                                }
                            });
                            return 0;
                        }

                        @Override
                        public int failed(String msg) {
                            return 0;
                        }
                    })
                    .execute(AppParams.getInstance().baseUrl + "/getKeyParams", beansIn.getJsonObject()
                            .toJSONString());
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

    private void checkInstallState() {
        try {
            Beans beansIn = new Beans();
            beansIn.getJsonObject()
                    .put("phone", AppParams.getInstance().appCurrentUser.getJsonObject()
                            .getString("phone"));
            File file = new File(AppParams.getInstance().mediaDir + "/installed");
            if (!file.exists()) {
                //首次安装
                beansIn.getJsonObject().put("deviceId", Tools.getUUID());
                AppParams.getNewNetWork()
                        .setInterface(new NetWorkInterface() {
                            @Override
                            public int success(String msg) {
                                requireActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {

                                            JSONObject msgFromServer = JSON.parseObject(msg);
                                            if (msgFromServer.getString("result").equals("成功")) {
                                                file.createNewFile();
                                            }
                                        } catch (Throwable e) {

                                        }
                                    }
                                });
                                return 0;
                            }

                            @Override
                            public int failed(String msg) {
                                return 0;
                            }
                        })
                        .execute(AppParams.getInstance().baseUrl + "/installSubmit", beansIn.getJsonObject()
                                .toJSONString());
            }
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }
}